<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Zipcode_manager extends PW_Controller{

    protected $_layout = 'admin';

    protected $_title = 'Zipcode Manager';

    public function index() {
        $this->redirect('import_zipcode');
    }

    /**
     * ACTION: Import zipcode from links of two excel files.
     *
     */
    public function import_zipcode() {
        $this->title('Import zipcode');
        $this->load->library('form_validation');

        $labels = array(
                'ken_all_url' => 'Ken_all URL',
                'jigyosyo_url'  => 'Jigyosyo URL',
                'remark' => 'Remark',
                'zipcode_apdatation_date' => 'Adaptation date'
        );

        $this->assign('labels', $labels);
        $this->_generate_form();

        // if $_POST values exist, do validation
        if ($values = $this->input->post()) {
            if ($this->_validate_form()) {
                $inputs =& $this->fetch('inputs');
                $params = array();

                // prepare params to insert
                foreach ($labels as $field => $label) {
                    $params[$field] = $values[$inputs[$field]['name']];
                }

                $this->db->trans_begin();

                //Process to import to table zipcode and zipcode adaptation.
                if($this->_process_import($params)){
                    //Redirect to list zipcode adaptation.
// 					$this->redirect('show');
                    $this->db->trans_commit();
                }
                else{
                    $this->assign('error_message', 'Please input valid url.');
                    $this->db->trans_rollback();
                }
            }
        }

        $this->_set_form_value(array('ken_all_url' => 'http://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip',
                'jigyosyo_url' => 'http://www.post.japanpost.jp/zipcode/dl/jigyosyo/zip/jigyosyo.zip'));
    }

    private  function _process_import($value){
        set_time_limit(600);
        $this->load->model('zipcode');

        //Clean old zipcode data.
        $current_date = date('Y-m-d');
        $this->zipcode->clean_old_data($current_date);

        //Create zipcode apdatation
        $zipcode_adaptatation_id = $this->zipcode->insert_zipcode_adaptation(array(
                'adaptation_date' => date('Y-m-d', strtotime($value['zipcode_apdatation_date'])),
                'remarks' => $value['remark'],
                'lastup_account_id' => 1));

        //Get current datetime from database mysql
        $current_datetime_db = $this->db->query('SELECT NOW() as datetime')->result_array();
        $current_datetime_db = $current_datetime_db[0]['datetime'];

        //Import two file zip to database.
        foreach(array("ken_all" => $value['ken_all_url'], "jigyosyo" => $value['jigyosyo_url']) as $key => $link){
            $newfile = 'temp/tmp_file.zip';

            //Copy two file from two links to temp folder.
            if (!copy($link, $newfile)) {
                return false;
            }

            //Extract to csv file.
            $zip = new ZipArchive();
            if ($zip->open($newfile, ZIPARCHIVE::CREATE)===TRUE) {
                $file_name = $zip->getNameIndex(0);
                $zip->extractTo('temp/');
                $zip->close();
            }
            else{
                return false;
            }

            //Delete zip file
            @unlink($newfile);
            $i = 0;

            //Set csv file to utf8.
            $file = file_get_contents("temp/" . $file_name);
            $detect = ($detect = mb_detect_encoding($file)) ? $detect : "auto";
            $file = mb_convert_encoding($file, ini_get("mbstring.internal_encoding"), $detect);
            file_put_contents("temp/" . $file_name, $file);
            unset($file, $detect);

            $file = fopen("temp/" . $file_name,"r");
            $i = 0;

            while(! feof($file)){
                $zipcode_data = fgetcsv($file);

                if($key == "ken_all"){
                    $zipcode_data_arr[] = array(
                            'zipcode_adaptation_id' => $zipcode_adaptatation_id,
                            'city_code' => ltrim($zipcode_data[0],'0'),
                            'zipcode_old'	=> ltrim($zipcode_data[1], '0'),
                            'zipcode'	=> ltrim($zipcode_data[2],'0'),
                            'pref_name'	=> $zipcode_data[6],
                            'pref_name_kana'	=> $zipcode_data[3],
                            'city_name'	=> $zipcode_data[7],
                            'city_name_kana'	=> $zipcode_data[4],
                            'town_name'	=> $zipcode_data[8],
                            'town_name_kana'	=> $zipcode_data[5],
                            'street_number'	=> "",
                            'office_name'	=> "",
                            'office_name_kana'	=> "",
                            'is_island'	=> 0,
                            'create_datetime' => $current_datetime_db,
                            'lastup_datetime' => $current_datetime_db
                    );
                }
                else{
                    $zipcode_data_arr[] = array(
                            'zipcode_adaptation_id' => $zipcode_adaptatation_id,
                            'city_code' => ltrim($zipcode_data[0], '0'),
                            'zipcode_old'	=> ltrim($zipcode_data[8], '0'),
                            'zipcode'	=> ltrim($zipcode_data[7], '0'),
                            'pref_name'	=> $zipcode_data[3],
                            'pref_name_kana'	=> "",
                            'city_name'	=> $zipcode_data[4],
                            'city_name_kana'	=> "",
                            'town_name'	=> $zipcode_data[5],
                            'town_name_kana'	=> "",
                            'street_number'	=> $zipcode_data[6],
                            'office_name'	=> $zipcode_data[2],
                            'office_name_kana'	=> $zipcode_data[1],
                            'is_island'	=> 0,
                            'create_datetime' => $current_datetime_db,
                            'lastup_datetime' => $current_datetime_db
                    );
                }

                //If traversed 1000 row, start insert batch, and set array to null.
                if($i == 1000){
                    $this->db->insert_batch('zipcode', $zipcode_data_arr);
                    $zipcode_data_arr = null;
                    $i = 0;
                }

                $i++;
            }

            //In case not have 1000 record but end ..
            if(!empty($zipcode_data_arr)){
                //Unset  redundant last empty row in array at last of each csv file.
                unset($zipcode_data_arr[count($zipcode_data_arr) - 1]);
                $this->db->insert_batch('zipcode', $zipcode_data_arr);
                $zipcode_data_arr = null;
            }

            fclose($file);
            //Delete temp file csv.
            @unlink('temp/' . $file_name );
        }

        return true;
    }

    /**
     * Generate all general form elements.
     *
     * Those elements are used in view. User has to decide which will be used
     * and which will not.
     */
    private function _generate_form($params = array(), $default = array()) {

        if (isset($params['action'])) {
            $this->assign('form_action', $params['action']);
        }

        $input_elements = array(
                'ken_all_url' => array(
                        'name'        => 'ken_all_url',
                        'id'          => 'ken_all_url',
                        'placeholder' => 'Data zipcode 1',
                        'class'       => 'input-xlarge',
                        'size' => 100
                ),
                'jigyosyo_url' => array(
                        'name'        => 'jigyosyo_url',
                        'id'          => 'jigyosyo_url',
                        'placeholder' => 'Data zipcode 2',
                        'class'       => 'input-xlarge',
                        'size' => 100
                ),
                'remark' => array(
                        'name'        => 'remark',
                        'id'          => 'remark',
                        'placeholder' => 'remark',
                        'class'       => 'input-xlarge',
                        'cols'	=> 50,
                        'rows' => 4
                ),
                'zipcode_apdatation_date' => array(
                        'name'        => 'zipcode_apdatation_date',
                        'id'          => 'zipcode_apdatation_date',
                        'placeholder' => 'Zipcode apdatation date',
                        'class'       => 'input-xlarge'
                ),
                'submit_button' => array(
                        'type'        => 'submit',
                        'name'        => 'action',
                        'value'       => 'submit',
                        'content'     => 'Submit',
                        'class'       => 'btn btn-primary'
                ),
                'cancel_button' => array(
                        'type'        => 'button',
                        'content'     => 'Cancel',
                        'class'       => 'btn',
                        'onclick'     => 'history.back()'
                )
        );

        if (isset($params['back_link'])) {
            $input_elements['cancel_button']['onclick'] = 'location.href="'. site_url($this->_module.'/'.trim($params['back_link']),'/') . '"';
        }

        $this->assign('inputs', $input_elements);

        $label_attr = array(
                'class' => 'control-label'
        );

        $this->assign('label_attr', $label_attr);
    }

    /**
     * Validate form.
     * Rules of all fields are set here.
     * Distinguish between insert and update by id.
     * @return boolean
     */
    private function _validate_form($update_id = false) {

        // using unique condition needs initializing database
        $labels =& $this->fetch('labels');
        $inputs =& $this->fetch('inputs');

        if ($update_id !== false) {
            $unique_str = '-' . $update_id;
        }

        $rules = array(
                'ken_all_url' => 'required|trim|valid_url|end_with[zip]',
                'jigyosyo_url'  => 'required|trim|valid_url|end_with[zip]',////////
                'remark'		  => 'required|trim',
                'zipcode_apdatation_date' => 'required|trim|is_unique[zipcode_adaptation.adaptation_date]|date_pattern[m/d/Y]'
        );

        $validate = array();
        foreach ($labels as $field => $label) {
            if (!isset($rules[$field])) {
                show_error($field . ' rules do not exist.');
            }

            $validate[] = array(
                    'field' => $inputs[$field]['name'],
                    'label' => $labels[$field],
                    'rules' => $rules[$field]
            );
        }

        $this->form_validation->set_rules($validate);

        if (!$this->form_validation->run()) {
            $this->form_validation->set_error_delimiters('<li>', '</li>');
            return false;
        }
        return true;
    }

    private function _set_form_value($default = array()) {
        $this->load->library('form_validation');
        $labels =& $this->fetch('labels');
        $inputs =& $this->fetch('inputs');

        foreach ($labels as $field => $label) {
            $inputs[$field]['value'] = $this->form_validation->set_value($inputs[$field]['name'], $default[$field]);
        }
    }
}

/* End of file zipcode_manager.php */
/* Location: {module_location}/admin/controllers/zipcode_manager.php */